package com.miyu.system.controller.user;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.miyu.system.pojo.system.SysUser;
import com.miyu.system.service.user.SysUserService;
import com.miyu.system.utils.enumeration.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 系统用户控制器
 * @author miyu
 */
@RestController
@RequestMapping("sys-user")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService userService;
    /**
     * 系统用户编辑
     * @param params 参数个数
     */
    @RequestMapping("sysUserEdit")
    public JSONObject sysUserEdit(@RequestBody JSONObject params){
        SysUser sysUser =  JSONObject.parseObject(params.toString(), SysUser.class);
        sysUser = userService.sysUserEdit(sysUser);
        return R.result("101");
    }

    /**
     * 查询系统用户
     * @return {@link JSONArray}
     */
    @RequestMapping("querySysUser")
    public Page<SysUser> querySysUser(@RequestBody JSONObject params){
        return userService.querySysUser(params);

   }

    /**
     * ▽系统用户
     * @param params 参数个数
     * @return {@link JSONObject}
     */
    @RequestMapping("delSysUser")
    public JSONObject delSysUser(@RequestBody JSONArray params){
        List<SysUser> sysUserList = JSONArray.parseArray(JSON.toJSONString(params), SysUser.class);

        return userService.delSysUser(sysUserList);
    }

    /**
     * 用户登录
     * @param params 参数个数
     * @return {@link JSONObject}
     */
    @RequestMapping("userLogin")
    public JSONObject userLogin(@RequestBody JSONObject params){
       return userService.userLogin(params);
    }

    /**
     * 用户退出
     * @return {@link JSONObject}
     */
    @RequestMapping("loginOut")
    public JSONObject loginOut(){
        return  userService.loginOut();
    }

    /**
     * 登录验证码
     * @param request  请求
     * @param response 响应
     * @return {@link HttpServletResponse}
     * @throws Exception 异常
     */
    @RequestMapping("checkCode")
    public HttpServletResponse checkCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
        GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(200, 100, 4);
        /*缓存验证码 5分钟过期*/
//        userService.checkCode(IpUtils.getIpAddr(),gifCaptcha.getCode());
        gifCaptcha.write(response.getOutputStream());
        return null;
    }
}
